//
//  XUSendController.m
//  新浪微博
//
//  Created by xuwenxin on 15-4-17.
//  Copyright (c) 2015年 xuwenxin. All rights reserved.
//

#import "XUSendController.h"
#import "XUEmotionController.h"
#import "XUEmotionModel.h"
#import "XUTextView.h"
#import "XUEmoticonSectionModel.h"
#import "XUTextAttachment.h"

@interface XUSendController () <UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UIBarButtonItem *sendButton;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toolbarLayout;
@property (weak, nonatomic) IBOutlet UIToolbar *toobarmanager;

@property (weak, nonatomic) IBOutlet XUTextView *textsend;
- (IBAction)close:(id)sender;

- (IBAction)send:(id)sender;
@end

@implementation XUSendController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.textsend.delegate = self;
//    self.textsend.allowsEditingTextAttributes = YES;
    
   
    self.sendButton.enabled = NO;
    // textView的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changLabel) name:UITextViewTextDidChangeNotification object:nil];
//   inputAccessoryView就是键盘顶部工具栏 这里没有用这个控件
//    self.textsend.inputAccessoryView = self.toobarmanager;
 
    // 键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changKeybord:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changKeybord:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
// 监听到通知
- (void)changLabel
{
    NSLog(@"接收到通知");
    if (self.textsend.text.length == 0) {
        self.textsend.content.text = @"";
        [self.textsend.content sizeToFit];
    } else {
        self.textsend.content.text = @"";
        [self.textsend.content sizeToFit];
        
    }
}

// NSNotification 的打印数据
/*
 NSConcreteNotification 0x7f9ef3ea8030 {
 name = UIKeyboardWillShowNotification;
 userInfo = {
 UIKeyboardAnimationCurveUserInfoKey    = 7;
 UIKeyboardAnimationDurationUserInfoKey = "0.25";
 UIKeyboardBoundsUserInfoKey            = "NSRect: {{0, 0}, {375, 258}}";
 UIKeyboardCenterBeginUserInfoKey       = "NSPoint: {187.5, 796}";
 UIKeyboardCenterEndUserInfoKey         = "NSPoint: {187.5, 538}";
 UIKeyboardFrameBeginUserInfoKey        = "NSRect: {{0, 667}, {375, 258}}";
 UIKeyboardFrameEndUserInfoKey          = "NSRect: {{0, 409}, {375, 258}}";
 }}
 */

#warning 没有加上键盘的节奏,需要调整
- (void)changKeybord:(NSNotification *)inf
{
    if ([inf.name isEqualToString:UIKeyboardWillShowNotification]) {
        NSDictionary *info = [inf userInfo];
        NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
        CGSize keyboardSize = [value CGRectValue].size;
        self.toolbarLayout.constant = keyboardSize.height;
        [UIView animateWithDuration:0.25 animations:^{
            [self.view layoutIfNeeded];
//            [self.toobarmanager layoutIfNeeded];
        }];
    } else {
        self.toolbarLayout.constant = 0;
        [UIView animateWithDuration:0.25 animations:^{
            [self.toobarmanager layoutIfNeeded];
        }];
    }
}

// 退出键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
    self.textsend.inputView = nil;
}
// 点击表情按钮(弹出表情键盘)
- (IBAction)emojiButton:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"XUEmotionKeyboard" bundle:nil];
#warning 键盘弹出有问题
    XUEmotionController *vc =sb.instantiateInitialViewController;
   
    // 输入
    __weak typeof(self) weakSelf = self;
    vc.myblock = ^(NSArray *emoticon,NSIndexPath *index){
        XUEmoticonSectionModel *sectionModel = emoticon[index.section];
        XUEmotionModel *model = sectionModel.sectionArray[index.item];
        
        [weakSelf showString:model];
        
    };
    
    [self.view endEditing:YES];
    self.textsend.inputView = nil;
    self.textsend.inputView = vc.view;
    [self.textsend becomeFirstResponder];
    
}

#warning 输入 需要重构
// 输入emoji表情
- (void)showString:(XUEmotionModel *)model
{
    // 先获取当前光标位置
    NSRange range = self.textsend.selectedRange;
    // 创建一个可变字符串初始化为当前文字
    NSMutableAttributedString *attributedM = [[NSMutableAttributedString alloc] initWithAttributedString:self.textsend.attributedText];
    // 标记光标需要改变的长度
    NSInteger attributeLength = 0;
    // 判断是否是自定义表情
    if (model.type.intValue == 0) {
        
        XUTextAttachment *textment = [[XUTextAttachment alloc] init];
        textment.image = [UIImage imageNamed:model.imgPath];
        
        NSAttributedString *attribute = [NSAttributedString attributedStringWithAttachment:textment];
        // 把需要显示的str插入到光标所在的位置
        [attributedM insertAttributedString:attribute atIndex:range.location];
        attributeLength = attribute.length;
        
    } else if (model.type.intValue == 1){
        NSString *str = model.code;
        // 格式化将要显示的str
        NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:str];
        // 把需要显示的str插入到光标所在的位置
        [attributedM insertAttributedString:attribute atIndex:range.location];
        attributeLength = str.length;
    } else {
        if (range.location == 0) return;
        [attributedM deleteCharactersInRange:NSMakeRange(range.location -1, 1)];
        attributeLength = -1;
    }
    
    // 重新计算文字长度
    NSUInteger length = range.location + attributeLength;
    // 重新设置文字
    self.textsend.attributedText = attributedM;
        // 将光标移动到 str的后面
    self.textsend.selectedRange = NSMakeRange(length,0);
    
//    paragraphStyle.lineSpacing = 8; //行距
    
//    UIFont *emojiFont = [UIFont fontWithName:@"AppleColorEmoji" size:35.0];
//    NSDictionary *attributes = @{ NSFontAttributeName:emojiFont};
//    self.textsend.font = emojiFont;
    
//    self.textsend.attributedText = [[NSAttributedString alloc]initWithString:self.textsend.text attributes:attributes];
    
}



/*
// 输入自定义表情
- (void)stringWithAttribute:(XUEmotionModel *)model
{
    
    // 先获取当前光标位置
    NSRange range = self.textsend.selectedRange;
    NSMutableAttributedString *attributedM = [[NSMutableAttributedString alloc] initWithAttributedString:self.textsend.attributedText];
    

    NSTextAttachment *textment = [[NSTextAttachment alloc] init];
    
    textment.image = [UIImage imageNamed:model.imgPath];
    
    NSAttributedString *attribute = [NSAttributedString attributedStringWithAttachment:textment];
//    [attributedM appendAttributedString:attribute];
    [attributedM insertAttributedString:attribute atIndex:range.location];
    
    self.textsend.attributedText = attributedM;
    // 重新计算文字长度
    NSUInteger length = range.location + attribute.length;
    // 将光标移动到 str的后面
    self.textsend.selectedRange = NSMakeRange(length,0);
    
}
 */

// 关闭按钮
- (IBAction)close:(id)sender {
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#warning 图文混排的格式,发送时需要重新包装格式
// 发送按钮
- (IBAction)send:(id)sender {
    NSLog(@"%@",self.textsend.text);
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];

    XUOuthModel *account = [XUOuthModel accountFromSandbox];
    parameters[@"access_token"] = account.access_token;

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:@"https://api.weibo.com/2/statuses/update.json" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"发布失败%@",error);
    }];
    
}
@end
